package com.example.demo.web;

import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.utils.SysUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName FileUpController
 * @Description
 * @Author 51
 * @Date 2019年11月28日 上午10:19:12
 */
@Slf4j
@Controller
@RequestMapping("/tool")
public class FileUpController {
    /**
     * @param req
     * @param picpaths
     * @return
     */
    @ResponseBody
    @RequestMapping("/upFile")
    public JSON articleUpFile(HttpServletRequest req, @RequestParam("editormd-image-file") MultipartFile picpaths) {
        String url = "blog/" + SysUtils.getDateStr() + "/";
        String realPath = req.getServletContext().getRealPath("/upload/");
        log.info("uploadFile is :{}", realPath);
// TomcatEmbeddedContext
        File file = new File(realPath, url);
        if (!file.exists() && file.mkdirs()) {
        }
        JSONObject resultJs = new JSONObject();
        String upPicFileName = SysUtils.getUpPicFileName();
        file = new File(file, upPicFileName);
        String contextPath = req.getServletContext().getContextPath();
        url = contextPath + "/upload/" + url + upPicFileName;
        try {
            picpaths.transferTo(file);
            /* resultJs.put("success", "1");此处不要写 字符串的"1"，只是写为数字不要带引号 */
            resultJs.put("success", 1);
            resultJs.put("message", "上传成功");
            resultJs.put("url", url);// 拼接自己的地址
        } catch (IllegalStateException | IOException e) {
            resultJs.put("success", 0);
            resultJs.put("message", "上传失败");
        }
        return resultJs;
    }

    /**
     * 上传到 nginx存储路径
     *
     * @param req
     * @param picpaths
     * @return
     */
    @ResponseBody
    @RequestMapping("/upFile/nginx")
    public JSON articleUpFileDemo(HttpServletRequest req, @RequestParam("editormd-image-file") MultipartFile picpaths) {
        String picPath = environment.getProperty("pic.Path");
        String picUrl = environment.getProperty("pic.Url");

        // 上传的文件原始名字
        String originalFilename = picpaths.getOriginalFilename();
        //获取文件后缀名|获取到的 是 "jpg"等
        String extension = FilenameUtils.getExtension(originalFilename);

        //构建文件路径|安装日期yyyyMMdd 分目录
        String url = "blog/" + SysUtils.getDateStr() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;
        JSONObject resultJs = new JSONObject();
        try {

            File file = new File(picPath, url);
            // TODO 可以自动创建不存在的文件夹
            FileUtils.copyInputStreamToFile(picpaths.getInputStream(), file);


            /* resultJs.put("success", "1");此处不要写 字符串的"1"，只是写为数字不要带引号 */
            resultJs.put("success", 1);
            resultJs.put("message", "上传成功");
            resultJs.put("url", picUrl + url);// 拼接自己的地址
        } catch (IllegalStateException | IOException e) {
            resultJs.put("success", 0);
            resultJs.put("message", "上传失败");
        }
        return resultJs;
    }

    //	获取配置文件中的值
    @Resource
    Environment environment;

    /**
     * * 在不知道文件名情况下获取上传文件
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "upfile", method = RequestMethod.POST)
    public @ResponseBody
    String uploadOssFile(MultipartFile file, HttpServletRequest request, Person person) {
        String picPath = environment.getProperty("pic.Path");
        String picUrl = environment.getProperty("pic.Url");
        log.info(StringUtils.repeat('-', 28));

        log.info("pserson:{}", person.toString());
        // String url = ossService.uploadOssFile(file);
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;

        Map<String, MultipartFile> fileMap = mr.getFileMap();
        Set<Map.Entry<String, MultipartFile>> entries = fileMap.entrySet();
        String url = null;
        for (Map.Entry<String, MultipartFile> entry : entries) {
            MultipartFile multipartFile = entry.getValue();
            String key = entry.getKey();
            url = multipartFile.getOriginalFilename();
            log.info("key-value|表单字段和文件名分别是|:{},{}", key, multipartFile.getOriginalFilename());
            try {
                // TODO 此方法无法自动创建不存在的文件夹
                // multipartFile.transferTo(new File(picPath +
                // multipartFile.getOriginalFilename()));

                // 文件保存
                url = SysUtils.getDateStrSpan_() + "/" + SysUtils.getDate4() + multipartFile.getOriginalFilename();
                // TODO 可以自动创建不存在的文件夹
                FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(picPath + url));
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.format("%s/%s", picUrl, url);
    }
}

class Person {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Person() {
        super();
    }

    /**
     * @param name
     * @param age
     */
    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

}
